using B.S.XZYData.Api.Wrter.Application.Command.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Plan
{
    /// <summary>
    /// 删除计划明细处理器
    /// </summary>
    public class DeletePlanItemsHandler : IRequestHandler<DeletePlanItemsCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<PlanItemModel> _planItemRepository;
        private readonly ILogger<DeletePlanItemsHandler> _logger;

        public DeletePlanItemsHandler(
            IBaseRepository<PlanItemModel> planItemRepository,
            ILogger<DeletePlanItemsHandler> logger)
        {
            _planItemRepository = planItemRepository;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(DeletePlanItemsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.ItemIds == null || !request.ItemIds.Any())
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "请选择要删除的明细项",
                        Data = false
                    };
                }

                // 检查明细项是否有完成数量
                var planItems = _planItemRepository.GetAll()
                    .Where(x => request.ItemIds.Contains(x.Id))
                    .ToList();
                var hasCompleted = planItems.Any(x => x.DoneQuantity > 0);

                if (hasCompleted)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "选中的明细项中有已完成数量的记录，不能删除",
                        Data = false
                    };
                }

                // 删除明细项
                int deleteCount = 0;
                foreach (var itemId in request.ItemIds)
                {
                    await _planItemRepository.DeleteAsync(itemId);
                    deleteCount++;
                }

                _logger.LogInformation($"成功删除计划明细 {deleteCount} 条，操作人：{request.OperateBy}");

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = $"成功删除 {deleteCount} 条明细记录",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除计划明细失败，操作人：{request.OperateBy}");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"删除失败：{ex.Message}",
                    Data = false
                };
            }
        }
    }
} 